import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Alert,
  Modal,
  message,
  Divider,
  Popconfirm,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './style.less';

const FormItem = Form.Item;
const { Option } = Select;

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, optionList, defaultData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (defaultData.sno) {
        handleAdd(fieldsValue, 'edit');
      } else {
        handleAdd(fieldsValue, 'add');
      }
    });
  };
  return (
    <Modal
      title="新建"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="学号">
        {form.getFieldDecorator('sno', {
          initialValue: defaultData.sno,
          rules: [{ required: true, message: '请输入学号' }],
        })(<Input placeholder="请输入学号" disabled={defaultData.id !== undefined ? true : false} />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="姓名">
        {form.getFieldDecorator('sname', {
          initialValue: defaultData.sname,
          rules: [{ required: true, message: '请输入姓名' }],
        })(<Input placeholder="请输入姓名" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="专业班级">
        {form.getFieldDecorator('classname', {
          initialValue: defaultData.classname,
          rules: [{ required: true, message: '请选择专业班级' }],
        })(
          <Select placeholder="请选择专业班级" style={{ width: '100%' }}>
            {optionList.map(item => {
              return (
                <Option key={item.id} value={item.classname}>
                  {item.classname}
                </Option>
              );
            })}
          </Select>
        )}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
        {form.getFieldDecorator('password', {
          initialValue: defaultData.password,
          rules: [{ required: true, message: '请输入密码' }],
        })(<Input placeholder="请输入密码" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="性别">
        {form.getFieldDecorator('sex', {
          initialValue: defaultData.sex,
          rules: [{ required: true, message: '请选择性别' }],
        })(
          <Select placeholder="请选择性别" style={{ width: '100%' }}>
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        )}
      </FormItem>
    </Modal>
  );
});

@connect(({ student, classes, loading }) => ({
  student,
  classes,
  loading: loading.effects['student/fetchStudentList'],
}))
@Form.create()
export default class StudentList extends PureComponent {
  state = {
    modalVisible: false,
    ItemData: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'student/fetchStudentList',
    });
    dispatch({
      type: 'classes/fetchClassList',
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'student/fetchStudentList',
      payload: {},
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'student/fetchStudentList',
        payload: fieldsValue,
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      ItemData: {},
    });
  };

  handleAdd = (record, flag) => {
    switch (flag) {
      case 'add':
        this.props
          .dispatch({
            type: 'student/addStudent',
            payload: record,
          })
          .then(message.success('添加成功'));
        break;
      case 'edit':
        this.props
          .dispatch({
            type: 'student/updateStudent',
            payload: record,
          })
          .then(message.success('编辑成功'));
        break;
      default:
        break;
    }
    this.setState({
      modalVisible: false,
    });
  };

  handleEdit = record => {
    this.setState({
      modalVisible: true,
      ItemData: record,
    });
  };

  handleRemove = record => {
    this.props.dispatch({
      type: 'student/removeStudent',
      payload: {
        sno: record.sno,
      },
    });
  };

  renderSimpleForm() {
    const { classes: { classList } } = this.props;
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="学号">
              {getFieldDecorator('sno')(<Input placeholder="请输入学号" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="专业班级">
              {getFieldDecorator('classname')(
                <Select placeholder="请选择专业班级" style={{ width: '100%' }}>
                  {classList.map(item => {
                    return (
                      <Option key={item.id} value={item.classname}>
                        {item.classname}
                      </Option>
                    );
                  })}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { loading, student: { studentList }, classes: { classList } } = this.props;
    const { modalVisible, ItemData } = this.state;
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
      optionList: classList,
      defaultData: ItemData,
    };
    const columns = [
      {
        title: '学号',
        key: 'sno',
        dataIndex: 'sno',
        align: 'center',
      },
      {
        title: '姓名',
        key: 'sname',
        dataIndex: 'sname',
        align: 'center',
      },
      {
        title: '密码',
        key: 'password',
        dataIndex: 'password',
        align: 'center',
        render: (text, record) => {
          return record.password;
        },
      },
      {
        title: '性别',
        key: 'sex',
        dataIndex: 'sex',
        align: 'center',
      },
      {
        title: '专业班级',
        key: 'classname',
        dataIndex: 'classname',
        align: 'center',
      },
      {
        title: '操作',
        align: 'center',
        dataIndex: 'operate',
        render: (text, record) => {
          return (
            <span>
              <a onClick={() => this.handleEdit(record)}>编辑</a>
              <Divider type="vertical" />
              <Popconfirm title="是否要删除此行？" onConfirm={() => this.handleRemove(record)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          );
        },
      },
    ];

    return (
      <PageHeaderLayout title="查看学生档案">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <Alert
              message={
                <Fragment>
                  <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                    添加用户
                  </Button>
                </Fragment>
              }
            />
            <Table
              rowKey={(record, index) => index}
              loading={loading}
              dataSource={studentList}
              columns={columns}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderLayout>
    );
  }
}
